package com.maysham.coder.server.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.maysham.coder.server.common.CoderException;
import com.maysham.coder.server.common.ExceptionCode;
import com.maysham.coder.server.dao.CodeDao;
import com.maysham.coder.server.dao.CodeRepo;
import com.maysham.coder.server.dao.GroupDao;
import com.maysham.coder.server.model.Code;
import com.maysham.coder.server.model.Group;
import com.maysham.coder.server.request.CodeCreateReq;
import com.maysham.coder.server.request.CodeUpdateReq;
import com.maysham.coder.server.service.CodeService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class CodeServiceImpl implements CodeService {
    @Resource
    private CodeDao codeDao;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private GroupDao groupDao;
    @Resource
    private CodeRepo codeRepo;

    @Override
    public Page<Code> codePage(String groupId, Pageable pageable) {
        return codeDao.page(groupId, pageable);
    }

    @Override
    public Code create(CodeCreateReq req) {
        Group group = groupDao.findById(req.getGroupId());
        if (!groupDao.existById(req.getGroupId())){
            throw new CoderException(ExceptionCode.GROUP_NOT_FOUND);
        }
        Code value = objectMapper.convertValue(req, Code.class);
        value.setGroup(group);
        return codeDao.insert(value);
    }

    @Override
    public Code update(CodeUpdateReq req) {
        if (!groupDao.existById(req.getGroupId())){
            throw new CoderException(ExceptionCode.GROUP_NOT_FOUND);
        }
        Code code = codeDao.findById(req.getId());
        if (code == null){
            throw new CoderException(ExceptionCode.CODE_LIB_NOT_FOUND);
        }
        code.setName(req.getName());
        code.setDescription(req.getDescription());
        code.setUrl(req.getUrl());
        code.setType(req.getType());
        return codeRepo.save(code);
    }


}
